<%#
 Copyright 2013-2018 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import React from 'react';
<%_ if (pagination === 'infinite-scroll') { _%>
import InfiniteScroll from 'react-infinite-scroller';
<%_ } _%>
import { connect } from 'react-redux';
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, <% if (searchEngine === 'elasticsearch') { %>InputGroup, <% } %>Col, Row, Table } from 'reactstrap';
<%_ if (searchEngine === 'elasticsearch') { _%>
import { AvForm, AvGroup, AvInput } from 'availity-reactstrap-validation';
<%_ } _%>
// tslint:disable-next-line:no-unused-variable
import {
  <%_ if (blobFields.length > 0) { _%>
    <%_ if (fieldsContainBlobOrImage) { _%>
  openFile,
    <%_ } _%>
  byteSize,
  <%_ } _%>
  Translate<% if (searchEngine === 'elasticsearch') { %>, translate, ICrudSearchAction<% } %>,
  ICrudGetAllAction<% if (fieldsContainDate) { %>, TextFormat<% } %>
  <%_ if (pagination !== 'no') { _%>
  , getSortState, IPaginationBaseState
  <%_ if (pagination === 'pagination' || pagination === 'pager') { _%>
  , getPaginationItemsNumber, JhiPagination
  <%_ }} _%>
} from 'react-jhipster';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import { IRootState } from 'app/shared/reducers';
import {
  <%_ if (searchEngine === 'elasticsearch') { _%>
  getSearchEntities,
  <%_ } _%>
  getEntities
  <%_ if (pagination === 'infinite-scroll') { _%>
  , reset
  <%_ } _%>
} from './<%= entityFileName %>.reducer';
import { I<%= entityReactName %> } from 'app/shared/model/<%= entityModelFileName %>.model';
 // tslint:disable-next-line:no-unused-variable
import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants';
<%_ if (pagination !== 'no') { _%>
import { ITEMS_PER_PAGE } from 'app/shared/util/pagination.constants';
<%_ } _%>

export interface I<%= entityReactName %>Props extends StateProps, DispatchProps, RouteComponentProps<{url: string}> {}

<% if (searchEngine === 'elasticsearch' && pagination !== 'no') { _%>
export interface I<%= entityReactName %>State extends IPaginationBaseState {
  search: string;
}
<%_ } else if (searchEngine === 'elasticsearch') { _%>
export interface I<%= entityReactName %>State {
  search: string;
}
<%_ } else if (pagination !== 'no') { _%>
export type I<%= entityReactName %>State = IPaginationBaseState;
<%_ } _%>

export class <%= entityReactName %> extends React.Component<I<%= entityReactName %>Props<% if (searchEngine === 'elasticsearch' || pagination !== 'no') { %>, I<%= entityReactName %>State<% } %>> {
  <%_ if (searchEngine === 'elasticsearch' || pagination !== 'no') { _%>
  state: I<%= entityReactName %>State = {
    <%_ if (searchEngine === 'elasticsearch') { _%>
    search: '',
    <%_ } _%>
    <%_ if (pagination !== 'no') { _%>
    ...getSortState(this.props.location, ITEMS_PER_PAGE)
    <%_ } _%>
  };
  <%_ } _%>

  componentDidMount() {
    <%_ if (pagination !== 'no') { _%>
      <%_ if (pagination === 'infinite-scroll') { _%>
      this.reset();
      <%_ } else { _%>
      this.getEntities();
      <%_ } _%>
    <%_ } else { _%>
    this.props.getEntities();
    <%_ } _%>
  }

  <%_ if (pagination === 'infinite-scroll') { _%>
  componentDidUpdate() {
    if (this.props.updateSuccess) {
      this.reset();
    }
  }
  <%_ } _%>

  <%_ if (searchEngine === 'elasticsearch') { _%>
  search = () => {
    if (this.state.search) {
      <%_ if (pagination === 'infinite-scroll') { _%>
      this.props.reset();
      <%_ } _%>
      <%_ if (pagination !== 'no') { _%>
      this.setState({ activePage: 1 }, () => {
        const { activePage, itemsPerPage, sort, order, search } = this.state;
        this.props.getSearchEntities(search, activePage - 1, itemsPerPage, `${sort},${order}`);
      });
      <%_ } else { _%>
      this.props.getSearchEntities(this.state.search);
      <%_ } _%>
    }
  };

  clear = () => {
    <%_ if (pagination === 'infinite-scroll') { _%>
    this.props.reset();
    <%_ } _%>
    this.setState({ search: ''<% if (pagination !== 'no') { %>, activePage: 1<% } %> }, () => {
      this.props.getEntities()
    });
  };

  handleSearch = event => this.setState({ search: event.target.value });
  <%_ } _%>

  <%_ if (pagination === 'infinite-scroll') { _%>
  reset = () => {
    this.props.reset();
    this.setState({ activePage: 1 }, () => {
      this.getEntities();
    });
  };

  handleLoadMore = () => {
    if (window.pageYOffset > 0) {
      this.setState({ activePage: this.state.activePage + 1 }, () => this.getEntities());
    }
  };
  <%_ } _%>

  <%_ if (pagination !== 'no') { _%>
  sort = prop => () => {
    this.setState(
      {
        order: this.state.order === 'asc' ? 'desc' : 'asc',
        sort: prop
      },
      () => <% if (pagination === 'infinite-scroll') { %>{ this.reset(); }<% } else { %>this.sortEntities()<% } %>
    );
  };

  <%_ if (pagination === 'pagination' || pagination === 'pager') { _%>
  sortEntities() {
    this.getEntities();
    this.props.history.push(`${this.props.location.pathname}?page=${this.state.activePage}&sort=${this.state.sort},${this.state.order}`);
  }
  <%_ } _%>

  <%_ if (pagination === 'pagination' || pagination === 'pager') { _%>
  handlePagination = activePage => this.setState({ activePage }, () => this.sortEntities());
  <%_ } _%>

  getEntities = () => {
    <%_ if (searchEngine === 'elasticsearch') { _%>
    const { activePage, itemsPerPage, sort, order, search } = this.state;
    if (search) {
      this.props.getSearchEntities(search, activePage - 1, itemsPerPage, `${sort},${order}`);
    } else {
      this.props.getEntities(activePage - 1, itemsPerPage, `${sort},${order}`);
    }
    <%_ } else { _%>
    const { activePage, itemsPerPage, sort, order } = this.state;
    this.props.getEntities(activePage - 1, itemsPerPage, `${sort},${order}`);
    <%_ } _%>
  };
  <%_ } _%>

  render() {
    const { <%=entityInstance %>List, match<% if (pagination === 'pagination' || pagination === 'pager') { %>, totalItems<% } %>} = this.props;
    return (
      <div>
        <h2 id="<%= entityFileName %>-heading">
          <Translate contentKey="<%= i18nKeyPrefix %>.home.title"><%= entityClassPluralHumanized %></Translate>
          <Link to={`${match.url}/new`} className="btn btn-primary float-right jh-create-entity" id="jh-create-entity">
            <FontAwesomeIcon icon="plus" />&nbsp;
            <Translate contentKey="<%= i18nKeyPrefix %>.home.createLabel">
              Create new <%= entityClassHumanized %>
            </Translate>
          </Link>
        </h2>
        <%_ if (searchEngine === 'elasticsearch') { _%>
        <Row>
          <Col sm="12">
            <AvForm onSubmit={this.search}>
              <AvGroup>
                <InputGroup>
                  <AvInput type="text" name="search" value={this.state.search} onChange={this.handleSearch}
                    placeholder=<% if (enableTranslation) { %>{translate('<%= i18nKeyPrefix %>.home.search')}<% } else { %>"Search"<% } %>/>
                  <Button className="input-group-addon">
                    <FontAwesomeIcon icon="search" />
                  </Button>
                  <Button type="reset" className="input-group-addon" onClick={this.clear}>
                    <FontAwesomeIcon icon="trash" />
                  </Button>
                </InputGroup>
              </AvGroup>
            </AvForm>
          </Col>
        </Row>
        <%_ } _%>
        <div className="table-responsive">
          <%_ if (pagination === 'infinite-scroll') { _%>
          <InfiniteScroll pageStart={this.state.activePage}
                          loadMore={this.handleLoadMore}
                          hasMore={this.state.activePage - 1 < this.props.links.next}
                          loader={<div className="loader">Loading ...</div>}
                          threshold={0}
                          initialLoad={false}>
          <%_ } _%>
          <Table responsive>
            <thead>
              <tr>
                <th<% if (pagination !== 'no') { %> className="hand" onClick={this.sort('id')} <%_ } _%>><Translate contentKey="global.field.id">ID</Translate><% if (pagination !== 'no') { %> <FontAwesomeIcon icon="sort" /><% } %></th>
                <%_ for (idx in fields) { _%>
                <th<% if (pagination !== 'no') { %> className="hand" onClick={this.sort('<%=fields[idx].fieldName%>')} <%_ } _%>><Translate contentKey="<%= `${i18nKeyPrefix}.${fields[idx].fieldName}` %>"><%= fields[idx].fieldNameHumanized %></Translate><% if (pagination !== 'no') { %> <FontAwesomeIcon icon="sort" /><% } %></th>
                <%_ } _%>
                <%_ for (idx in relationships) { _%>
                    <%_ if (relationships[idx].relationshipType === 'many-to-one'
                    || (relationships[idx].relationshipType === 'one-to-one' && relationships[idx].ownerSide === true)
                    || (relationships[idx].relationshipType === 'many-to-many' && relationships[idx].ownerSide === true && pagination === 'no')) {
                    const fieldName = dto === 'no' ? "." + relationships[idx].otherEntityField : relationships[idx].otherEntityFieldCapitalized;_%>
                <th<% if (pagination !== 'no') { %> <% } %>><Translate contentKey="<%= `${i18nKeyPrefix}.${relationships[idx].relationshipName}` %>"><%= relationships[idx].relationshipNameHumanized %></Translate><% if (pagination !== 'no') { %> <FontAwesomeIcon icon="sort" /><% } %></th>
                    <%_ } _%>
                <%_ } _%>
                <th />
              </tr>
            </thead>
            <tbody>
              {
                <%= entityInstance %>List.map((<%=entityInstance %>, i) => (
                <tr key={`entity-${i}`}>
                  <td>
                    <Button tag={Link} to={`${match.url}/${<%=entityInstance %>.id}`} color="link" size="sm">
                      {<%= entityInstance %>.id}
                    </Button>
                  </td>
                  <%_ for (idx in fields) {
                    const fieldType = fields[idx].fieldType;
                    const fieldName = fields[idx].fieldName;
                    const fieldIsEnum = fields[idx].fieldIsEnum;
                  _%>
                  <td>
                  <%_ if (fieldType === 'Boolean') { _%>
                    {<%= entityInstance %>.<%=fields[idx].fieldName%> ? 'true' : 'false'}
                  <%_ } else if (fieldType === 'Instant' || fieldType === 'ZonedDateTime') { _%>
                    <TextFormat type="date" value={<%= entityInstance %>.<%=fieldName%>} format={APP_DATE_FORMAT} />
                  <%_ } else if (fieldType === 'LocalDate') { _%>
                    <TextFormat type="date" value={<%= entityInstance %>.<%=fieldName%>} format={APP_LOCAL_DATE_FORMAT} />
                  <%_ } else if (fieldIsEnum && enableTranslation) { _%>
                    <Translate contentKey={`<%= angularAppName %>.<%= fieldType %>.${<%= entityInstance %>.<%= fieldName %>}`} />
                  <%_ } else if (['byte[]', 'ByteBuffer'].includes(fieldType)) { _%>
                    <%_
                      // blobFields
                      const fieldBlobType = fields[idx].fieldTypeBlobContent;
                      if (fieldBlobType !== 'text') {
                    _%>
                      {<%= entityInstance %>.<%= fieldName %> ? (
                        <div>
                            <a onClick={openFile(<%= entityInstance %>.<%= fieldName %>ContentType, <%= entityInstance %>.<%= fieldName %>)}>
                            <%_ if (fieldBlobType === 'image') { _%>
                              <img src={`data:${<%= entityInstance %>.<%= fieldName %>ContentType};base64,${<%= entityInstance %>.<%= fieldName %>}`} style={{ maxHeight: '30px' }} />
                            <%_ } else { _%>
                              <Translate contentKey="entity.action.open">Open</Translate>
                            <%_ } _%>
                            &nbsp;
                          </a>
                          <span>{<%= entityInstance %>.<%= fieldName %>ContentType}, {byteSize(<%= entityInstance %>.<%= fieldName %>)}</span>
                        </div>
                      ) : null}
                    <%_ } else { _%>
                        {<%= entityInstance %>.<%= fieldName %>}
                    <%_ } _%>
                  <%_ } else { _%>
                    {<%= entityInstance %>.<%= fieldName %>}
                  <%_ } _%>
                  </td>
                  <%_ } _%>
                  <%_ for (idx in relationships) {
                    const relationshipType = relationships[idx].relationshipType;
                    const ownerSide = relationships[idx].ownerSide;
                    const relationshipFieldName = relationships[idx].relationshipFieldName;
                    const relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
                    const otherEntityName = relationships[idx].otherEntityName;
                    const otherEntityStateName = relationships[idx].otherEntityStateName;
                    const otherEntityField = relationships[idx].otherEntityField;
                    const otherEntityFieldCapitalized = relationships[idx].otherEntityFieldCapitalized; _%>
                    <%_ if (relationshipType === 'many-to-one'
                    || (relationshipType === 'one-to-one' && ownerSide === true)
                    || (relationshipType === 'many-to-many' && ownerSide === true && pagination === 'no')) { _%>
                  <td>
                    <%_ if (otherEntityName === 'user') { _%>
                      <%_ if (relationshipType === 'many-to-many') { _%>
                    {
                      (<%= entityInstance %>.<%= relationshipFieldNamePlural %>) ?
                          (<%= entityInstance %>.<%= relationshipFieldNamePlural %>.map((val, j) =>
                              <span key={j}>{val.<%= otherEntityField %>}{(j === <%= entityInstance %>.<%= relationshipFieldNamePlural %>.length - 1) ? '' : ', '}</span>
                          )
                      ) : null
                    }
                      <%_ } else { _%>
                        <%_ if (dto === 'no') { _%>
                    {<%= entityInstance + "." + relationshipFieldName %> ? <%= entityInstance + "." + relationshipFieldName + "." + otherEntityField %> : ''}
                        <%_ } else { _%>
                    {<%= entityInstance + "." + relationshipFieldName + otherEntityFieldCapitalized %> ? <%= entityInstance + "." + relationshipFieldName + otherEntityFieldCapitalized %> : ''}
                          <%_ } _%>
                      <%_ } _%>
                      <%_ } else { _%>
                        <%_ if (relationshipType === 'many-to-many') { _%>
                      {
                        (<%= entityInstance %>.<%= relationshipFieldNamePlural %>) ?
                            (<%= entityInstance %>.<%= relationshipFieldNamePlural %>.map((val, j) =>
                                <span key={j}><Link to={`<%= otherEntityStateName %>/${val.id}`}>{val.<%= otherEntityField %>}</Link>{(j === <%= entityInstance %>.<%= relationshipFieldNamePlural %>.length - 1) ? '' : ', '}</span>
                            )
                        ) : null
                      }
                        <%_ } else { _%>
                            <%_ if (dto === 'no') { _%>
                      {<%= entityInstance + "." + relationshipFieldName %> ?
                      <Link to={`<%= otherEntityStateName %>/${<%= entityInstance + "." + relationshipFieldName + ".id}" %>`}>
                        {<%= entityInstance + "." + relationshipFieldName + "." + otherEntityField %>}
                      </Link> : ''}
                            <%_ } else { _%>
                      {<%= entityInstance + "." + relationshipFieldName + otherEntityFieldCapitalized %> ?
                      <Link to={`<%= otherEntityStateName %>/${<%= entityInstance + "." + relationshipFieldName + "Id}" %>`}>
                        {<%= entityInstance + "." + relationshipFieldName + otherEntityFieldCapitalized %>}
                      </Link> : ''}
                            <%_ } _%>
                        <%_ } _%>
                      <%_ } _%>
                    </td>
                    <%_ } _%>
                    <%_ } _%>
                    <td className="text-right">
                      <div className="btn-group flex-btn-group-container">
                        <Button tag={Link} to={`${match.url}/${<%=entityInstance %>.id}`} color="info" size="sm">
                          <FontAwesomeIcon icon="eye" /> <span className="d-none d-md-inline" ><Translate contentKey="entity.action.view">View</Translate></span>
                        </Button>
                        <Button tag={Link} to={`${match.url}/${<%=entityInstance %>.id}/edit`} color="primary" size="sm">
                          <FontAwesomeIcon icon="pencil-alt" /> <span className="d-none d-md-inline"><Translate contentKey="entity.action.edit">Edit</Translate></span>
                        </Button>
                        <Button tag={Link} to={`${match.url}/${<%=entityInstance %>.id}/delete`} color="danger" size="sm">
                          <FontAwesomeIcon icon="trash" /> <span className="d-none d-md-inline"><Translate contentKey="entity.action.delete">Delete</Translate></span>
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))
              }
            </tbody>
          </Table>
          <%_ if (pagination === 'infinite-scroll') { _%>
          </InfiniteScroll>
          <%_ } _%>
        </div>
        <%_ if (pagination === 'pagination' || pagination === 'pager') { _%>
        <Row className="justify-content-center">
          <JhiPagination
            items={getPaginationItemsNumber(totalItems, this.state.itemsPerPage)}
            activePage={this.state.activePage}
            onSelect={this.handlePagination}
            maxButtons={5}
          />
        </Row>
        <% } _%>
      </div>
    );
  }
}

const mapStateToProps = ({ <%= entityInstance %> }: IRootState) => ({
  <%= entityInstance %>List: <%= entityInstance %>.entities,
  <%_ if (pagination !== 'no') { _%>
  totalItems: <%= entityInstance %>.totalItems,
  <%_ } _%>
  <%_ if (pagination === 'infinite-scroll') { _%>
  links: <%= entityInstance %>.links,
  entity: <%= entityInstance %>.entity,
  updateSuccess: <%= entityInstance %>.updateSuccess,
  <%_ } _%>
});

const mapDispatchToProps = {
 <%_ if (searchEngine === 'elasticsearch') { _%>
 getSearchEntities,
 <%_ } _%>
 getEntities,
 <%_ if (pagination === 'infinite-scroll') { _%>
 reset
 <%_ } _%>
};

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

export default connect(mapStateToProps, mapDispatchToProps)(<%= entityReactName %>);
